﻿package com.cilico.components;

import com.cilico.ConfigManager;
import com.cilico.utils.ConstantRepository;
import com.cilico.utils.Utils;
import com.cilico.utils.StringTicker;
import com.cilico.view.BaseView;
import com.cilico.view.FormLayout;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Paint.Style;
import android.text.TextPaint;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

/**
 * CheckBox控件
 * 
 * @author lv.xiangan
 *
 */
public class cCheckBox extends CheckBox implements Component, CompoundButton.OnCheckedChangeListener {
	private int TEXT_MARGIN; // will add image width
	public CssStyle cssStyle_;
	int textColor_; // normal text color.
	public int left_; // Relative left position to the left of the FULL canvas.
	public int top_; // Relative left position to the top of the FULL canvas.
	public int width_;
	public int height_;
	public int marginTop_;
	public int marginBottom_;
	private String text_;
	public String attrName_;
	public String attrValue_;
	public String inputName_;//需要联动的输入框的名字
	public String[] relaEnable_;
	public String[] relaDisable_;
	public String[] relaVisible_;
	public String[] relaInvisible_;
	public String isEncrypt_;
	public boolean isChecked_;
	public TextPaint paint_;
	public BaseView bv_;
	public boolean focus_;
	public String backValue_;
	private int marginLeft_;
	private int marginRight_;
	private boolean isInTable_;
	private Bitmap checkedImg_;
	private Bitmap unCheckedImg_;
	FormLayout fLayout_;

	public cCheckBox(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		bv_ = (BaseView) context;
		TEXT_MARGIN = 5;
		paint_ = new TextPaint();
		paint_.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_SMALL));
		createImgs();
		calcuHeight();
		setOnCheckedChangeListener(this);
		textColor_ = Color.BLACK;
	}

	public cCheckBox(Context context, String text) {
		// TODO Auto-generated constructor stub
		super(context);
		bv_ = (BaseView) context;
		TEXT_MARGIN = 5;
		text_ = text;
		paint_ = new TextPaint();
		paint_.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_SMALL));
		createImgs();
		calcuHeight();
		setOnCheckedChangeListener(this);
		textColor_ = Color.BLACK;
	}

	private void createImgs() {
		checkedImg_ = ConstantRepository.getCheckBoxIcon(true, bv_);
		unCheckedImg_ = ConstantRepository.getCheckBoxIcon(false, bv_);
	}

	static cCheckBox createCheckBox(String text, Context context) {
		cCheckBox chbx = new cCheckBox(context);
		chbx.setText(text);
		return chbx;
	}

	void setText(String text) {
		text_ = text;
		super.setText(text);
	}

	public String getContentText() {
		return super.getText().toString();
	}

	public void setContentText(String text) {
		// TODO Auto-generated method stub
		this.setText(text);
	}

	public void settleComponets(BaseView bv, int index) {
		// TODO Auto-generated method stub
		Utils.settleComponetsChild(bv, this.isChecked(), relaEnable_, relaDisable_, relaVisible_, relaInvisible_,
				this);
	}

	boolean keyGameAction(int keyCode) {
		if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
			pointerPressed(0, 0);
		}
		return false;
	}

	void pointerPressed(int x, int y) {
		setChecked();
		bv_.tabBar_.getContentLayout().invalidate();
	}

	void setChecked() {
		isChecked_ = !isChecked_;
		if (this.isChecked())
			this.setChecked(false);
		else
			this.setChecked(true);
	}

	public void shrinkWidth() {
		LinearLayout.LayoutParams vgl = (LayoutParams) getLayoutParams();
		if (null == vgl) {
			vgl = new LinearLayout.LayoutParams(width_, height_);
			this.setLayoutParams(vgl);
		}
		int widthBeforeText = ConstantRepository.getCheckBoxIcon(false, bv_).getWidth() + TEXT_MARGIN + marginLeft_ + marginRight_;
		int textWidth = 0;
		if (text_ != null) {
			BaseView.setTypeFace(paint_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
			textWidth = (int) paint_.measureText(text_);
		}
		int width = textWidth + widthBeforeText + 2;
		if (width >= width_) {
			setWidth(Math.min(width, MAX_WIDTH));
		} else {
			setWidth(width);
		}

	}

	public void setWidth(int width) {
		super.setWidth(width);
		width_ = width;
		this.getLayoutParams().width = width;
	}

	/**
	 * Calculate the height of this CheckBox.
	 */
	private void calcuHeight() {
		marginTop_ = 0;
		marginBottom_ = 5;
		int imgH = 0;
		if (checkedImg_ != null && unCheckedImg_ != null) {
			imgH = checkedImg_.getHeight();
		}
		height_ = Math.max(imgH, (int) (paint_.getTextSize())) + marginTop_ + marginBottom_;
	}

	public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(width_, height_);
	}

	protected void onDraw(Canvas g) {
		// 设置字体非抗锯齿效果，使字体边界更平滑
		paint_.setAntiAlias(true);
		text_ = this.getText().toString();
		int posX = left_;
		int posY = top_;
		/*
		 * paint icon.
		 */
		posX += marginLeft_;
		posY += marginTop_ + marginBottom_;
		Bitmap temp = null;
		if (null != checkedImg_ && unCheckedImg_ != null) {
			// 如果客户端保留有多选框图片，则以图片绘制
			try {
				if (this.isChecked())
					temp = checkedImg_;
				else
					temp = unCheckedImg_;
				g.drawBitmap(temp, posX, posY, paint_);
			} catch (Exception ex) {
				Utils.printException(ex);
			}

		} else {
			// 客户端没有多选框图片，进行代码绘制
			int x = posX;
			int h = (int) paint_.getTextSize();
			int y = top_ + h >> 3;
			int w = h;
			// 圆角矩形圆角弧度
			int radian = 10;
			// 控件未获得焦点
			Shader shader;
			if (this.isChecked()) {
				shader = new LinearGradient(0, y, 0, y + h, new int[] { ConfigManager.COLOR_WHITE, ConfigManager.COLOR_DKGREEN }, null, Shader.TileMode.MIRROR);
			} else {
				shader = new LinearGradient(0, y, 0, y + h, new int[] { ConfigManager.COLOR_DKGRAY, ConfigManager.COLOR_WHITE }, null, Shader.TileMode.MIRROR);
			}
			// 绘制框背景
			paint_.setShader(shader);
			paint_.setStyle(Style.FILL);
			g.drawRoundRect(new RectF(x, y, x + w, y + h), radian, radian, paint_);

			// 清空渐变效果
			paint_.setShader(null);
			paint_.setColor(ConfigManager.COLOR_GREEN);

			if (this.isChecked()) {
				// 绘制选中后的勾图标
				Path p = new Path();
				int w1 = w >> 1;
				int w2 = w >> 2;
				int w3 = w >> 3;
				int h1 = h >> 1;
				int h2 = h >> 2;
				int h3 = h >> 3;
				p.moveTo(x + w2, y + h1 - h3);
				p.lineTo(x + w1 - 2, y + h1 + h3);
				p.cubicTo(x + w1 - 2, y + h1 + h3, x + 3 * w2, y + h / 6, x + w + w2, y - h2);
				p.cubicTo(x + w + w2, y - h2, x + w + w2, y + h2 - 1, x + w + w2 + 3, y + h2);
				p.cubicTo(x + w + w2 + 3, y + h2, x + 7 * w3 - 2, y + 3 * h3 - 1, x + w1 - 2, y + h);
				p.cubicTo(x + w1 - 2, y + h, x + w3, y + 5 * h3, x - 3, y + h1 + 2);
				p.close();
				g.drawPath(p, paint_);
			}
			if (this.isFocused()) {
				// 用单色绘制外包围选择框
				paint_.setStyle(Style.STROKE);
				g.drawRoundRect(new RectF(x - 1, y - 1, x + w + 1, y + h + 1), radian, radian, paint_);
			}

		}

		/*
		 * paint text.
		 */
		if (null == temp) {
			posX = height_ + TEXT_MARGIN;
		} else {
			posX += temp.getWidth() + TEXT_MARGIN;
		}
		posY = top_ + marginTop_;
		paint_.setColor(textColor_);

		if (text_ != null) {

			if (focus_) {
				BaseView.setTypeFace(paint_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
				StringTicker.instance().drawMoveStr(this, g, width_ - TEXT_MARGIN, paint_, textColor_, text_, posX,
						(int) (posY + paint_.getTextSize()));
			}
			if (this.isFocusable() && this.isFocused()) {
				BaseView.setTypeFace(paint_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
				StringTicker.instance().drawMoveStr(this, g, width_ - TEXT_MARGIN, paint_, textColor_, text_, posX,
						(int) (posY + paint_.getTextSize()));
			} else {
				BaseView.setTypeFace(paint_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
				g.drawText(Utils.abbrevString(text_, paint_, width_ - TEXT_MARGIN), posX,
						posY + paint_.getTextSize(), paint_);
			}
		}
	}

	public void cleanText() {
		// TODO Auto-generated method stub

	}

	public void setFocus(boolean isFocus, int i) {
		// TODO Auto-generated method stub
		focus_ = isFocus;
	}

	// 焦点改变时调用该方法
	protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
		if (gainFocus) {
			BaseView bv = (BaseView) this.getContext();
			bv.stopTicker();
		}
		super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
	}

	public void mould() {
		CssStyle cs = cssStyle_;
		// set the width.
		if (cs != null && cs.width_ > 0) {
			setWidth(cs.width_);
		}

		// set the height
		if (cs != null && cs.height_ > 0) {
			setHeight(cs.height_);
		}

		// set the text color.
		if (cs != null && cs.fgColor_ != 0) {
			setTextColor(cs.fgColor_);
			textColor_ = cs.fgColor_;
		}
		// set the font family (since API Level 4)
		/*
		 * String fontPath = ConfigManager.getFontPath(cbStyle.fontFamily_); if (fontPath != null) {
		 * temp.setTypeface(Typeface.createFromFile(fontPath)); }
		 */
		// set the font size.
		if (cs != null && cs.fontSize_ > 0) {
			setTextSize(cs.fontSize_);
		}
		// set the background color.
		if (cs != null && cs.bgColor_ != 0) {
			setBackgroundColor(cs.bgColor_);
		}

		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width_, height_);
		setLayoutParams(lp);
	}

	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub

	}

	public void setCmpWidth(int width) {
		// TODO Auto-generated method stub

	}

	public void setCssStyle(CssStyle style) {
		cssStyle_ = style;
	}

	public View getCmpView() {
		return this;
	}

	public int getCmpHeight() {
		return height_;
	}

	public int getCmpWidth() {
		return width_;
	}

	public void setInTable(boolean inTable) {
		isInTable_ = inTable;
	}

	public boolean isInTable() {
		return isInTable_;
	}

	public CssStyle getCssStyle() {
		return cssStyle_;
	}

	public void releaseResource(View view) {
		// TODO Auto-generated method stub
		// cssStyle_ = null;
		// text_ = null;
		// attrName_ = null;
		// attrValue_ = null;
		// relaEnable_ = null;
		// relaDisable_ = null;
		// relaVisible_ = null;
		// relaInvisible_ = null;
		// paint_ = null;
		// backValue_ = null;

		if (null != checkedImg_ && !checkedImg_.isRecycled()) {
			checkedImg_.recycle();
		}
		checkedImg_ = null;
		if (null != unCheckedImg_ && !unCheckedImg_.isRecycled()) {
			unCheckedImg_.recycle();
		}
		unCheckedImg_ = null;
	}

	public void setForm(FormLayout fl) {
		// TODO Auto-generated method stub
		fLayout_ = fl;
	}

	public FormLayout getForm() {
		// TODO Auto-generated method stub
		return fLayout_;
	}

	@Override
	public void setEncrypt(String encrypt) {
		// TODO Auto-generated method stub
		isEncrypt_ = encrypt;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if (attrName_ != null && attrName_.equalsIgnoreCase("allCheck")) {
			isChecked_ = isChecked;
			setChecked(isChecked);
			final int sizeMid = bv_.vWidgetArray_.size();
			Object o = null;
			for (int i = 0; i < sizeMid; i++) {
				// 得到界面中层管理框架中的单个子元素
				o = bv_.vWidgetArray_.elementAt(i);
				if (o instanceof cCheckBox) {
					cCheckBox checkboxView = (cCheckBox) o;
					checkboxView.setChecked(isChecked);
					bv_.tabBar_.invalidate();
				}
			}
		} else {
			setChecked(isChecked);
//			此处要取到checkBox联动的输入框
			final int sizeMid = bv_.vWidgetArray_.size();
			Object o = null;
			for (int i = 0; i < sizeMid; i++) {
				// 得到界面中层管理框架中的单个子元素
				o = bv_.vWidgetArray_.elementAt(i);
				if (o instanceof mTextField) {
					mTextField tf = (mTextField)o;
					if (tf.attrName_.equals(inputName_)) {
						if (isChecked) {
							tf.setText(attrValue_);
						} else {
							tf.setText("");
						}
						
						tf.setEnabled(!isChecked);
						break;
					}
				}
			}
		}
		
	}
}
